UNPKG

studiocms

Version:

Astro Native CMS for AstroDB. Built from the ground up by the Astro community.

68 lines (67 loc) 2.28 kB
import { apiResponseLogger } from "studiocms:logger"; import pluginList from "studiocms:plugins"; import { settingsEndpoints } from "studiocms:plugins/endpoints"; import { AllResponse, createEffectAPIRoutes, createJsonResponse, Effect, genLogger, OptionsResponse, pipe } from "../../../../../effect.js"; const { POST, OPTIONS, ALL } = createEffectAPIRoutes( { POST: (ctx) => genLogger("studiocms/routes/api/dashboard/plugins/[plugin].POST")(function* () { const userData = ctx.locals.StudioCMS.security?.userSessionData; if (!userData?.isLoggedIn) { return apiResponseLogger(403, "Unauthorized"); } const isAuthorized = ctx.locals.StudioCMS.security?.userPermissionLevel?.isAdmin === true; if (!isAuthorized) { return apiResponseLogger(403, "Unauthorized"); } const { plugin } = ctx.params; const settingsPage = yield* Effect.try({ try: () => pipe( pluginList.filter(({ settingsPage: settingsPage2 }) => !!settingsPage2), (p) => p.find(({ identifier }) => identifier === plugin), (p) => { if (!p) { return apiResponseLogger(404, "Plugin not found"); } const settingsPage2 = settingsEndpoints.find( ({ identifier }) => identifier === plugin ); if (!settingsPage2) { return apiResponseLogger(404, "Plugin does not have a settings page"); } return settingsPage2; } ), catch: (cause) => new Error("An error occurred while fetching plugin settings page", { cause }) }); if (settingsPage instanceof Response) { return settingsPage; } if (!settingsPage.onSave) { return apiResponseLogger(404, "Plugin does not have a settings page"); } return settingsPage.onSave(ctx); }), OPTIONS: () => Effect.try(() => OptionsResponse({ allowedMethods: ["POST"] })), ALL: () => Effect.try(() => AllResponse()) }, { cors: { methods: ["POST", "OPTIONS"] }, onError: (error) => { console.error("API Error:", error); return createJsonResponse({ error: "Internal Server Error" }, { status: 500 }); } } ); export { ALL, OPTIONS, POST };